import {
  addAllWebsiteApi,
  updateWebsiteApi,
  getAllWebsiteTypesByConditionApi,
  deleteUsersApi,
  getWebsitesPageApi,
  updateUserAppConfigApi,
  addUserApi,
  uploadFileApi,
  getAllRolesApi
} from '@/services'
import { pick } from 'lodash'
import {
  Button,
  Card,
  Form,
  Icon,
  InputNumber,
  InputText,
  Message,
  Modal,
  Page,
  Select,
  Table,
  Upload,
  Image,
  useData,
} from 'magic-ui-react'
import { ModalHandle } from 'magic-ui-react/dist/Modal/interface'
import { ActionType, ColumnType } from 'magic-ui-react/dist/Table/interface'
import { useEffect, useRef, useState } from 'react'
import styles from './styles.module.less'
import { TableDataType } from './types'

const UsersList = () => {

  const modalRef = useRef<ModalHandle>()
  const actionRef = useRef<ActionType>()

  const [form] = Form.useForm()

  const [pagination, setPagination] = useState({
    total: 0
  })
  const [title, setTitle] = useState('')
  const [avatar, setAvatar] = useState('')
  const [options, setOptions] = useState([])

  const columns: ColumnType<TableDataType>[] = [

    {
      title: '用户',
      dataKey: 'username',
      bodyCellRender(column, record, index) {
        return (
          <div className='flex gap-5'>
            <Image
              preview
              width={40}
              height={40}
              src={record.avatar}
            />
            <div>
              <div className='font-semibold'>{record.username}</div>
              <div className='text-slate-500'>{record.name}</div>
            </div>
          </div>

        )
      },
    },
    {
      title: '年龄',
      dataKey: 'age'
    },
    {
      title: '电话',
      dataKey: 'phone'
    },
    {
      title: '邮箱',
      dataKey: 'email'
    },
    {
      title: '创建时间',
      dataKey: 'createdTime',
      width: 200,
    },
    {
      title: '更新时间',
      dataKey: 'updateTime',
      width: 200,
    },
    {
      title: '操作',
      width: 200,
      dataKey: 'operation',
      bodyCellRender: (_columns, record) => {
        return (
          <div className='flex gap10'>
            <Button
              type='primary'
              onClick={() => {
                setTitle('修改')
                setAvatar(record.avatar)
                modalRef.current?.open()
                setTimeout(() => {
                  form.setFieldsValue({ ...record })
                }, 0)
              }}
            >编辑</Button>
            <Button
              status='error'
              onClick={() => {
                deleteItem(record)
              }}
            >删除</Button>
          </div>
        )
      }
    },
  ]

  const onOK = async () => {
    try {
      const requestData = form.getFields()
      if (requestData._id) {
        await updateUserAppConfigApi(
          requestData._id,
          {
            ...pick(requestData, ['name', 'phone', 'email', 'age', 'username', 'role']),
            avatar,
          }
        );
      } else {
        await addUserApi({
          ...requestData,
          avatar,
        });
      }
      modalRef.current?.close()
      actionRef.current?.refresh()
    } catch (error) {
    }
  }


  const deleteItem = async (record: any) => {
    try {
      await deleteUsersApi([record._id])
      Message.success('删除成功');
      actionRef.current?.refresh()
    } catch (error) {

    }
  }

  const getOptions = async () => {
    try {
      let res = await getAllRolesApi()
      let newOptions = res.data.map((item: any) => {
        return {
          label: item.roleName,
          value: item._id,
        }
      })
      setOptions(newOptions)
    } catch (error) {

    }
  }

  useEffect(() => {
    getOptions()
  }, [])

  return (
    <Page className={styles.UsersList}>
      <Table
        search={{
          columns: [
            {
              formItem: {
                name: 'name',
                label: '名称'
              },
              type: 'text'
            },
          ]
        }}
        oprationContent={(
          <Card borders={[]}>
            <div className='flex'>
              <Button
                type='primary'
                icon={<Icon icon="add" />}
                onClick={() => {
                  setTitle('添加')
                  setAvatar('');
                  modalRef.current?.open()
                }}
              >
                添加
              </Button>
            </div>
          </Card>
        )}
        actionRef={actionRef}
        borderWidth={0}
        columns={columns}
        data={async (pagination, search) => {
          let list: any[] = []
          try {
            const res: any = await getWebsitesPageApi({
              ...pagination,
              ...search,
            });
            list = res.data
            setPagination({
              total: res.total!
            })
            return {
              list,
              total: res.total!,
            }
          } catch (error) {
            return {
              list,
              total: 0,
            }
          }
        }}
        pagination={{
          sort: ['page'],
          ...pagination
        }}
      />
      <Modal title={title} onOK={onOK} ref={modalRef}>
        <Form
          form={form}
          layout='vertical'
        >
          <Upload
            onChange={async (files) => {
              try {
                const res = await uploadFileApi(files)
                setAvatar(res.data)
              } catch (error) {
              }
            }}
          >
            {(files) => {
              return (
                <Image
                  imgAttributes={{
                    style: {
                      objectFit: 'cover'
                    },
                  }}
                  width={100}
                  height={100}
                  src={files?.[0] ? URL.createObjectURL(files?.[0]) : ''}
                  defaultSrc={avatar}
                />
              )
            }}
          </Upload>
          <Form.Item label="用户名" name='username'>
            <InputText />
          </Form.Item>
          <Form.Item label="姓名" name='name'>
            <InputText />
          </Form.Item>
          <Form.Item label="年龄" name='age'>
            <InputNumber />
          </Form.Item>
          <Form.Item label="手机号码" name='phone'>
            <InputText />
          </Form.Item>
          <Form.Item label="邮箱" name='email'>
            <InputText />
          </Form.Item>
          <Form.Item label="角色" name='role'>
            <Select
              options={options}
            />
          </Form.Item>
          {title === '修改' || (
            <Form.Item label="密码" name='password'>
              <InputText />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </Page>
  )
}
export default UsersList